package com.leetcode.search;

/**
 * leetcode 200 岛屿的数量
 */
public class Solution200 {
    public int numIslands(char[][] grid) {
        if (grid == null) {
            return 0;
        }

        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '1') {
                    dfs(grid, i, j);
                    count++;
                }
            }
        }

        return count;
    }

    private void dfs(char[][] grid, int row, int column) {
        if (row < 0 || row >= grid.length
                || column < 0 || column >= grid[row].length
                || grid[row][column] == '#'
                || grid[row][column] == '0') {
            return;
        }

        grid[row][column] = '#';
        // 上
        dfs(grid, row - 1, column);
        // 下
        dfs(grid, row + 1, column);
        // 左
        dfs(grid, row, column - 1);
        // 右
        dfs(grid, row, column + 1);
    }

    public static void main(String[] args) {
        Solution200 solution200 = new Solution200();
        char[][] grid = new char[][]{
                {'1', '1', '0', '0', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '1', '0', '0'},
                {'0', '0', '0', '1', '1'}};
        System.out.println(solution200.numIslands(grid));
    }
}
